<?php
/**
 *@author sparkguo 
 *@date 2017-09-22   bonanza订单下载抓取
 */
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('max_execution_time', '0');
class Bonanzaapi extends CI_Controller {
    
    public $dev_name = 'jrNUJmxg6aIsZbB';
    public $cert_name = 'CAjrkROW4t5zpyi';
    public $tabaoApiUrl='https://eco.taobao.com/router/rest';
    
	function __construct(){
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Bonanzaapi_m','m');
  
		$this->pageSize =$this->config->item('pagenum');
    } 
    
    public function request(){
        $action = $other = $this->input->get_post('op');
		switch($action){
			case "jsonGetToken":
                $this->jsonGetToken();
				break; 
			case "getShopAuth":
                $this->getShopAuth();
                break; 
			case "saveAuth":
                $this->saveAuth();  
            break;
            case "getsku":
				$this->getApiGoodInfo();
			break; 
			case "get_order_list":
                $bon_shop_type=$this->fun->getdatabasesdetail("db_platform"," AND name='Bonanza'");
                $bonanza_shop=$this->db->get_where("d_shop","platfrom='{$bon_shop_type['id']}' 
                  and refresh_token is not null and access_token is not null and amazonkey=1")->result_array();//and name='bonanza-CS'
                foreach($bonanza_shop as $key=>$shopinfo){
                    dump($shopinfo['name']);
                    $this->dev_name=$shopinfo['appkey'];
                    $this->cert_name=$shopinfo['appsecret'];
                    $starttime=$this->input->get("starttime");
                    $endtime=$this->input->get("endtime");
                    if(!empty($starttime) && !empty($endtime)){
                        $insertdata=$this->getOrderList($shopinfo,1,$starttime."T00:00:00Z",$endtime."T23:59:00Z");//2017-09-08T00:00:00Z            
                    }else{
                        $insertdata=$this->getOrderList($shopinfo,1);//2017-09-08T00:00:00Z     
                    }   
                }
                echo "订单抓取完成";
            break; 
            case "complateOrders":
                $this->setOrderShipment();
            break;
		}
    }
    
    //保存授权信息
    public function saveAuth(){
        $id  = $this->input->post('bo_shop_id');
        $post_data=$this->input->post();
        $save_data=array('aliexpressData'=>$post_data['platfromname'],'appkey'=>$post_data['boappkey'],
        'appsecret'=>$post_data['boappsecret'],'access_token'=>$post_data['access_token'],
        'refresh_token'=>$post_data['refresh_token'],'amazonkey'=>$post_data['openflag']);
        $sql = "SELECT * FROM d_shop WHERE id = $id ";
        $rs  = $this->db->query($sql)->row_array();
        $history_url=$_SERVER['HTTP_REFERER'];
        if($rs['platfromname']=='Bonanza'){
            $this->db->where('id',$id);
            $this->db->update('d_shop',$save_data);
            echo "<script language='javascript'>alert('授权设制保存成功');location.href='$history_url'</script>";
        }else{
            echo "<script language='javascript'>alert('非法操作');;location.href='$history_url'</script>";
        }   
    }
    
    public function getApiGoodInfo(){
        $itemid=$this->input->get('itemid');
        $dev_name = "jrNUJmxg6aIsZbB";
        $cert_name = "CAjrkROW4t5zpyi";
        $url = "http://api.bonanza.com/api_requests/standard_request";
        $headers = array("X-BONANZLE-API-DEV-NAME: " .$dev_name, "X-BONANZLE-API-CERT-NAME: " .$cert_name);
        $args = array("itemId" =>$itemid);
        $request = $this->buildRequest("getSingleItem",$args);
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$request,
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "curl error\n";
          exit(2);
        }
        curl_close($connection);
        $response = json_decode($json_response,true);
        dump($response);
    }
    

    //获取店铺授权信息
    public function getShopAuth(){
        $id  = $this->input->post('shop_id');
        $sql = "SELECT * FROM d_shop WHERE id = $id ";
        $rs  = $this->db->query($sql)->row_array();
        echo json_encode($rs);
    }
    //获取店铺令牌
    public function jsonGetToken(){
        $dev_id=$this->input->post("appkey");
        $cert_id=$this->input->post("appsecret");
        $token_info=$this->gettoken($dev_id,$cert_id);
        if(!empty($token_info['fetchTokenResponse']['authToken'])){
            $ret_data=array('state'=>'success','data'=>$token_info,'msg'=>'ok'); 
               
        }else{
            $ret_data=array('state'=>'error','data'=>$token_info,'msg'=>'token返回异常，请联系管理员检查');       
        }
        echo json_encode($ret_data);
        
    }
    
    public function gettoken($dev_name,$cert_name){
        $url = "https://api.bonanza.com/api_requests/secure_request";
        $headers = array("X-BONANZLE-API-DEV-NAME: " .$dev_name, "X-BONANZLE-API-CERT-NAME: " .$cert_name);
        $args = array();
        $post_fields = "fetchTokenRequest";
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "curl error\n";
          exit(2);
        }
        curl_close($connection);
        $response = json_decode($json_response,true);
        $token = $response['fetchTokenResponse']['authToken'];
        return $response;
    }
    
    
    //获取订单列表
    public function getOrderList($shopdata,$page_number=1,$createTimeFrom=0,$createTimeTo=0){

        $shopinfo= $shopdata;
        $token=$shopinfo['access_token'];//'aECfuQ84Q3';
        if($createTimeFrom==0){
            $createTimeFrom=date("Y-m-d",strtotime("-3 day"))."T00:00:00Z";
        }
        if($createTimeTo==0){
            $createTimeTo=date("Y-m-d")."T".date("H:i:s")."Z";
        }
        
        $args = array('createTimeFrom'=>$createTimeFrom,'createTimeTo'=>$createTimeTo,'sellerInfo' => array('feedbackRatingStar'=>'blue'),'paginationInput'=>array('entriesPerPage'=>10,'pageNumber'=>$page_number));
        $args['requesterCredentials']['bonanzleAuthToken'] = $token;   // only necessary if specifying an itemStatus other than "for_sale"
        $request = $this->buildRequest("getOrders",$args);
        $json_response = $this->apiCall($request);
        $response = json_decode($json_response,true);
        echo $request;
        dump($response);
        $totalpage= $response['getOrdersResponse']['paginationResult']['totalNumberOfPages'];
        $totaldata=$response['getOrdersResponse']['paginationResult']['totalNumberOfEntries'];
        //echo $totalpage;
        $platforminfo = $this->fun->getdatabasesdetail("db_platform"," AND `name`='Bonanza'");
        if($response['ack']=='Success'){
			$order_list=$response['getOrdersResponse']['orderArray'];
			foreach($order_list as $k=>$rs){
			     $arr_order_list=array();
                $v=$rs['order'];
                $buy_goods=$v['itemArray'];
                $shipinfo=$v['shippingAddress'];
                $shipdetal=$v['shippingDetails'];
                $transinfo=$v['transactionArray']['transaction'];
                $ship_price=$v['shippingDetails'];
				$sql_order = "SELECT * FROM db_order_list WHERE tradeid = '{$v['orderID']}' ";
				$rs_order = $this->db->query($sql_order)->row_array();
				if($rs_order){
					continue;
				}
                if(in_array($v['orderStatus'], array('Proposed','Cancelled'))){
                    continue;
                }
                $country_code=strtoupper(trim($shipinfo["country"]));
                $country_code=$country_code==''?'USD':$country_code;
                //获取国家名称与信息
				$countryinfo = $this->fun->getdatabasesdetail("d_country"," AND countryid='".$country_code."'");
                //汇率
                $exchange=$this->db->get_where("d_moneyrate","name='{$country_code}'")->result_array();
                if($exchange[0]["rate"]==''){
                    $exchange=$this->db->get_where("d_moneyrate","name='US'")->result_array();
                }
    			$exchangerate=$exchange[0]["rate"];
                
            	$this->load->library('amazondata');
				$arr_order_list['order_sn'] = $this->amazondata->getNo('bonanza',$v['orderID'],$shopinfo['id']);//生成订单序号
				$arr_order_list['dates']  = date("Y-m-d"); //当天日期 判断order_sn使用
				$arr_order_list['ordertime']  = date("Y-m-d H:i:s",strtotime($v['createdTime'])); //订单日期时间
				$arr_order_list['order_source']  = "正常订单"; //默认
				$arr_order_list['customerid']  = $v['buyerUserName']; //客户id
				$arr_order_list['consignee']  =$shipinfo['name']; //收货人
				$arr_order_list['country']  = $countryinfo['countrynamecn'];
				$arr_order_list['country_code']  = $shipinfo['country']; //国家
				$arr_order_list['country_cn']  = $countryinfo['countrynameen']; //国家英文
				$arr_order_list['province']  = $shipinfo['stateOrProvince'];
				$arr_order_list['city']  = $shipinfo['cityName'];
				$arr_order_list['address']  = $shipinfo['street1']." ".$shipinfo["street2"];
				//$arr_order_list['address2']  = $v['address2'];
				$arr_order_list['zipcode']  = $shipinfo['postalCode'];
                
				$arr_order_list['tel']  = '';//平台无电话
				//$arr_order_list['mobile']  = $v['mobileNo'];
				$arr_order_list['shopid']  = $shopinfo['id']; //店铺id
				$arr_order_list['shopname']  = $shopinfo['name'];
				$arr_order_list['shopoper']  = $shopinfo['updateoper'];//店铺负责人
               	
                
				$arr_order_list['moneytype']  = 'USD';//货币类型
				$arr_order_list['tradeid']  = $v['orderID']; //交易单号
				$arr_order_list['goods_originask']  = $v['subtotal']; //订单金额
				$arr_order_list['goods_amount']  = $v['total']*$exchangerate;
                
				$arr_order_list['shipping_originask']  =$ship_price['amount']; //原始快递费
				$arr_order_list['shipping_fee']  =$arr_order_list['shipping_originask']*$exchangerate; //物流费 人民币
				
				$arr_order_list['pay_fee']  =$arr_order_list['goods_amount'] * 0.015; //支付费用
                $arr_order_list['email'] = $transinfo['buyer']['email']; //
				$arr_order_list['platform_fee']  = $transinfo['finalValueFee']*$exchangerate; //平台费用
				$arr_order_list['add_time'] = time();
				$arr_order_list['saleschannel']  = 'Bonanza';
                $arr_order_list['platformID']  = $platforminfo['id'];//
                $arr_order_list['moneyrate']  = $exchangerate;//当前汇率
                
				$arr_order_list['order_status']  = 2; //已支付
                $arr_order_list['payid']  = $transinfo['providerID'];
                if(is_numeric($arr_order_list['address'])){
                    $arr_order_list['order_status']  = 7; //待审核    
                    $arr_order_list['remark']="收货地址异常：街道全是数字";
                }

				//留言
				if($v['buyerCheckoutMessage']){
					$arr_order_list['platform_message']  = $v['buyerCheckoutMessage']; //备注
				}
				$this->db->trans_begin();	//事务开始
				$this->db->insert('db_order_list',$arr_order_list);
                echo $this->db->last_query()."<br />";
				$insert_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
				//更新日志记录
				$imgdata["goods_id"] = $insert_id;	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'bonanza接口新增订单,交易ID='.$v['orderID'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);
                
                //卖出物品信息存入
				$error_flag =0;
                $weighttotal=0;
                $count_price=0;
				foreach($buy_goods as $key=>$value){
				    $goodsinfo=$value['item'];
					$arr_order_sell['order_id'] = $insert_id;
                    $arr_order_sell['goods_weight']=0;
                    if(empty($goodsinfo["sku"])){
					    $arr_order_sell['goods_id'] = 0;
                        $error_flag=1;
                    }else{
                        /*$parent_goods = $this->fun->getdatabasesdetail("db_goods_parent"," and p_parent_sku='".$goodsinfo['sku']."'");
                        if($parent_goods){
                            $buygoods_size=explode(" ",trim($goodsinfo['variations']['variation'][0]['nameValueList']['value']));
                            $buygoods_size=$buygoods_size[count($buygoods_size)-1];
                            $rgoods = $this->fun->getdatabasesdetail("db_goods",
                            " and goods_parentID='".$parent_goods['p_parent_id']."' and goods_sku like '%-{$buygoods_size}'");
                        }
                        if($rgoods['goods_id']==''){*/
                            $rgoods = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".$goodsinfo['sku']."'");    
                        //}
                        if($rgoods){
                            $goodsinfo['sku']=$rgoods['goods_sku'];
                        }
                        if($rgoods["goods_id"]==null){
                            $error_flag=1;
                        }
                        $rgoods["goods_id"]=$rgoods["goods_id"]==null?0:$rgoods["goods_id"];
                        $arr_order_sell['goods_id']=$rgoods["goods_id"];
                        $arr_order_sell['costprice'] = empty($rgoods['g_costprice'])?'':$rgoods['g_costprice'];//物品成本价
                        $rgoods["g_weight"]=$rgoods["g_weight"]==null?0:$rgoods["g_weight"];
                        $weight = $rgoods["g_weight"];
                        $arr_order_sell['goods_weight'] = $weight;//毛重
                        $weighttotal+=$weight;
                    } 
                    if($key+1>=count($buy_goods)){
                        $goodsinfo['price']=($v['total']-$arr_order_list['shipping_originask']-$count_price)/$goodsinfo['quantity'];      
                    }else{
                        $count_price+=$goodsinfo['price']*$goodsinfo['quantity'];  
                    }
                        
                    $goodsinfo['sku']=empty($goodsinfo['sku'])?'':$goodsinfo['sku'];
                    $arr_order_sell['goods_name'] = $goodsinfo['title'];
                    $sizeinfo='';
                    if(is_array($goodsinfo['variations']['variation'])){
                        foreach($goodsinfo['variations']['variation'] as $sizekey=>$sizeval){
                            $sizeinfo.=" ".$sizeval['nameValueList']['name'].":".$sizeval['nameValueList']['value'];    
                        }
                        $sizeinfo=trim($sizeinfo);
                    }
                    
                    $sizeinfo=$sizeinfo==":"?"":$sizeinfo;
                    $arr_order_sell['goods_sn'] = $goodsinfo['sku'];
                    $arr_order_sell['sale_remark']=$sizeinfo;
					$arr_order_sell['goods_number'] = $goodsinfo['quantity']; //商品数量
					$arr_order_sell['originsellprice'] = $goodsinfo['price'];
                    $arr_order_sell['goods_price'] = $goodsinfo['price']*$exchangerate;
                    $arr_order_sell['originsku'] = $goodsinfo['sku'];//原始sku
					$arr_order_sell['goods_amount'] =$goodsinfo['price']*$goodsinfo['quantity']*$exchangerate;
					$this->db->insert('db_order_sell',$arr_order_sell);
                    echo $this->db->last_query()."<br />";
                    echo'成功导入一条订单'.$arr_order_list['order_sn'].'<br />';
					$insert_sell_id = $this->db->insert_id(); //也就是db_order_sell 中order_id
		
				}
				if($error_flag || $arr_order_sell['goods_weight']>0 ){
					$this->db->where('order_id',$insert_id);
                    if($error_flag){
                        $data['order_status'] = 7;    
                    }
					$data['orderweight'] = $weighttotal;
					$this->db->update('db_order_list',$data);
				}
				//若执行成功，则提交
				if ($this->db->trans_status() === FALSE){
					$this->db->trans_rollback();
				}else{
					$this->db->trans_commit();
				}
			};  
        }

        //echo "totalpage".$totalpage;
        if($page_number<$totalpage){
            $page_number+=1;
            $this->getOrderList($shopinfo,$page_number,$createTimeFrom,$createTimeTo);
        }else{
            return $totaldata;
        }
    }
    
    //更新订单物流交运信息
    //@param  orderid 订单id号 db_order_list 或者去轮询查找该速卖通店铺的相关订单
    public function setOrderShipment(){
        $order_id = $this->input->get('order_id'); //如果传入单个参数话,就只行该单个参数，否则执行相关循环
        //店铺相关操作
        $fileds = " id,appkey,appsecret,refresh_token,refresh_timeout,access_token,access_timeout ";
        $sql_shop = "SELECT $fileds FROM d_shop WHERE platfromname = 'Bonanza'  ORDER BY id DESC ";
        $rs_shop = $this->db->query($sql_shop)->result_array();
        $shop_where = " (";
        $arr_shop = array();
        if(count($rs_shop)>0){
            foreach($rs_shop as $k_shop=>$v_shop){
                $shop_where.= $v_shop['id'].",";
                $arr_shop[$v_shop['id']] = $v_shop;
            }
            $shop_where = trim($shop_where,",");
            $shop_where.=")";
        }else{
            exit("没有经过令牌授权的店铺!");
        }
        //获取所有订单列表
        $where = " WHERE (order_status = 4 or order_status = 5) AND is_update_platform = 0 "; //4为已发货状态 is_update_platform为未与线上同步
        $where .= " AND shipping_name is not null AND shipping_number is not null ";
        if($order_id){
            $where.=" AND order_id = '{$order_id}' ";
        }
        $where.= " AND shopid in $shop_where ";
        //$where.=" limit 0,100 "; //可以限定执行一次获取多少条数据
        $sql_mabangorder = "SELECT order_id,shipping_name,shopid,tradeid,shipping_number FROM db_order_list ".$where;
        $rs_mabangorder = $this->db->query($sql_mabangorder)->result_array();
        echo $this->db->last_query()."<br />";
    
        //dump($rs_mabangorder);
        if(count($rs_mabangorder)>0){
            $time=time(); //当前时间
            foreach($rs_mabangorder as $k=>$v){
                if(!$v['shipping_name']){
                    continue;
                }
                if(!$v['shipping_number']){
                    continue;
                }
                //验证授权以及数字签名来创建订单
                $arr_app_check = $arr_shop[$v['shopid']];
            //dump($arr_app_check);
                //判断生存期限仅十个小时的access_token是否过期，过期则通过refresh_token重新获取
                if ($time <(int)$arr_app_check['access_timeout']) {
                    $access_token = $arr_app_check['access_token'];
                }else{
                    exit("店铺{$arr_app_check[name]}令牌已过有效期，请重新获取令牌并授权!");    
                }
                $appKey = $arr_app_check['appkey'];
                $appScret = $arr_app_check['appsecret'];
                $usertoken=$arr_app_check['access_token'];
                                
                $this->dev_name=$arr_app_check['appkey'];
                $this->cert_name=$arr_app_check['appsecret'];
                
                switch($v['shipping_name']){
                	case "E邮包线下上海":
                        $buyer_note="Tracking Site: http://www.17track.net/en/track?nums=".$v['shipping_number'];
                		break; 
                	case "顺丰速运":
                        $buyer_note="Tracking Site: http://www.sf-express.com/us/en/dynamic_function/waybill/#search/bill-number/".$v['shipping_number'];  
                        break; 
                    case "DHL":
                        $buyer_note="Tracking Site: http://www.dhl.com/en/express/tracking.html?AWB=".$v['shipping_number'];//Tracking Site: http://www.dhl.com/en/express/tracking.html?AWB=
                        break;
                    case "UBI澳洲":
                        $buyer_note="tracking site: http://smartparcel.gotoubi.com/home";
                    break;
                }
        
                //拼接api签名相关参数 填写发货通知
                if($v['shipping_name']=="UPS"){
                    $v['shipping_name'] = "ups";
                }elseif($v['shipping_name']=="E邮包线下上海"){
                    $v['shipping_name'] = "usps";
                }else{
                    $v['shipping_name'] = "international";    
                }
                //查询物流key
                //$sql_key = "SELECT * FROM db_order_express WHERE name = '{$v['shipping_name']}' ";
                //$rs_key = $this->db->query($sql_key)->row_array();
                //'notes'=>$buyer_note,
                $args = array('transactionID'=>$v['tradeid'],
                'shipment'=>array('shippingTrackingNumber'=>$v['shipping_number'],'notes'=>$buyer_note,'privateNote'=>'mark of myself','shippingCarrierUsed'=>$v['shipping_name']));
                $args['requesterCredentials']['bonanzleAuthToken'] = $usertoken; 
                
                $request = $this->buildRequest("completeSale",$args);
                $json_response = $this->apiCall($request);
                $result = json_decode($json_response,true);
                dump($request);
                echo "result:";
                dump($result);

                //var_dump($result);exit;
                if($result['ack']=="Success"){
                    $this->db->where('order_id',$v['order_id']);
                    $arr_plat['is_update_platform']=1;
                    $this->db->update('db_order_list',$arr_plat); //说明已经同步过

                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $v['order_id'];	//订单ID db_order_list
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = 0;
                    $imgdata["types"] = 3;
                    $imgdata["content"] = 'Bonanza接口自动同步交运信息至线上成功,交易ID='.$v['tradeid'];
                    $imgdata["createUser"] ='auto';
                    $this->db->insert('db_goods_log', $imgdata);
                    echo $this->db->last_query();
                }else{
                    echo"订单".$v['order_sn'].'更新线上交运信息失败<br />';
                }
                print_r($sign_data);echo "<br/>";

               // return $result['success']; //返回true
            }
        }else{
            exit("暂时无运单信息可同步至线上!");
        }

    }
    
    function buildRequest($api_call_name, $assoc_array) {
      $request_name = $api_call_name . "Request";
      $json = json_encode($assoc_array);
      $request = $request_name . "=" .  $json;
      return $request;
    }
     
    function apiCall($api_call_and_args,$server_url="https://api.bonanza.com/api_requests/secure_request") {
        $dev_name = $this->dev_name;
        $cert_name = $this->cert_name;
        $url =$server_url;
        $headers = array("X-BONANZLE-API-DEV-NAME: " .$dev_name, "X-BONANZLE-API-CERT-NAME: " .$cert_name);
        $resp =$this->sendHttpRequest($url,$headers, $api_call_and_args);
        return $resp;
    }
    
    function sendHttpRequest($url, $headers, $post_fields) {
        $args = array();
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
        //CURLOPT_SSLVERSION=>CURL_SSLVERSION_TLSv1, CURLOPT_SSL_CIPHER_LIST =>"TLSv1",
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "\n";
          exit(2);
        }
        curl_close($connection);
        return $json_response;
    }
    
    
    function getAllOrders(){
        
    }
    
    
    public function NumToStr($num) {
        if (stripos($num, 'e') === false)
            return $num;
        $num = trim(preg_replace('/[=\'"]/', '', $num, 1), '"'); //出现科学计数法，还原成字符串
        $result = "";
        while ($num > 0) {
            $v = $num - floor($num / 10) * 10;
            $num = floor($num / 10);
            $result = $v . $result;
        }
        return $result;
    }


    
    function tbHttpRequest($url, $headers, $post_fields) {
        $args = array();
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
        CURLOPT_SSLVERSION=>CURL_SSLVERSION_TLSv1, CURLOPT_SSL_CIPHER_LIST =>"TLSv1",
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "\n";
          exit(2);
        }
        curl_close($connection);
        return $json_response;
    }
}
